<?php

namespace App\Jobs;

use App\Enums\DnsType;
use App\Facades\AliyunDns;
use App\Models\Ssl;

class AliyunDomainLetsEncrypt extends BaseJob
{
    public function __construct(protected Ssl $ssl)
    {
    }

    public function handle(): void
    {
        if (!$this->ssl->order_id) {
            return;
        }

        $acme = app('acme');
        $order = $acme->getOrder($this->ssl->order_id);
        # 1. 确认订单
        $authorizations = $acme->authorize($order);
        $txtRecord = $authorizations[0]->getTxtRecord();
        $value = $txtRecord->getValue();
        $rr = rtrim(str_replace($this->ssl->root, '', $txtRecord->getName()), '.');
        $this->ssl->state = '1-ORDERED';
        $this->ssl->save();

        # 2. DNS解析
        AliyunDns::aliyun($this->ssl->aliyun)->store($this->ssl->root, $rr, $value, DnsType::TXT);
        $this->ssl->state = '2-RR';
        $this->ssl->save();

        # 3. DNS校验
        $challenge = $authorizations[0]->getDnsChallenge();
        $acme->validate($challenge);

        if ($acme->isReady($order)) {
            $certificate = $acme->getCertificate($order);

            $this->ssl->state       = '3-READY';
            $this->ssl->certs       = [
                'csr'          => $certificate->getCsr(),
                'chain'        => $certificate->getCertificate(),
                'certificate'  => $certificate->getCertificate(false),
                'intermediate' => $certificate->getIntermediate(),
                'privateKey'   => $certificate->getPrivateKey(),
            ];
            $this->ssl->expiry_date = $certificate->getExpiryDate();
        } else {
            $this->ssl->state = '3-FAILED';
        }
        $this->ssl->save();
    }
}
